package com.yf.thumbbackend.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yf.thumbbackend.constant.ThumbConstant;
import com.yf.thumbbackend.entity.Blog;
import com.yf.thumbbackend.entity.Thumb;
import com.yf.thumbbackend.entity.User;
import com.yf.thumbbackend.entity.dto.DoThumbRequest;
import com.yf.thumbbackend.exception.BusinessException;
import com.yf.thumbbackend.mapper.ThumbMapper;
import com.yf.thumbbackend.service.BlogService;
import com.yf.thumbbackend.service.ThumbService;
import com.yf.thumbbackend.service.UserService;
import com.yf.thumbbackend.util.RedisKeyUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

/**
* @author echo-sp
* @description 针对表【thumb】的数据库操作Service实现
* @createDate 2025-04-18 20:27:12
*/
@Service("thumbServiceDB")
@RequiredArgsConstructor
public class ThumbServiceImpl extends ServiceImpl<ThumbMapper, Thumb>
    implements ThumbService{

    @Resource
    private UserService userService;
    @Resource
    private BlogService blogService;

    @Resource
    private TransactionTemplate transactionTemplate;

    private final RedisTemplate<String,Object> redisTemplate;



    @Override
    public Boolean doThumb(DoThumbRequest doThumbRequest, HttpServletRequest request) {
        //校验
        if(doThumbRequest == null || doThumbRequest.getId() == null){
            throw  new BusinessException(400,"参数异常");
        }
        //获取登录用户
        User loginUser = userService.getLoginUser(request);
        //加锁
        synchronized (loginUser.getId().toString().intern()){
            //编程式事务
            transactionTemplate.execute(status -> {
                //查询当前用户是否点赞
//                boolean exists = this.lambdaQuery()
//                        .eq(Thumb::getUserId, loginUser.getId())
//                        .eq(Thumb::getBlogId, doThumbRequest.getId())
//                        .exists();
                boolean exists = this.hasThumb(doThumbRequest.getId(),loginUser.getId());
                if(exists){
                    throw new BusinessException(400,"已经点赞过了");
                }
                //新增点赞记录
                //添加blog点赞数
                boolean update = blogService.update()
                        .setSql("thumbCount = thumbCount + 1")
                        .eq("id", doThumbRequest.getId())
                        .update();
                //添加点赞记录
                Thumb thumb = new Thumb();
                thumb.setBlogId(doThumbRequest.getId());
                thumb.setUserId(loginUser.getId());
             boolean success = update &&  this.save(thumb);
             //如果点赞成功将 记录存放在redis中
                if(success){
                    redisTemplate.opsForHash().put(ThumbConstant.USER_THUMB_KEY_PREFIX +loginUser.getId(),doThumbRequest.getId().toString(),thumb.getId());
                }
                return success;
            });
        }
        return true;
    };;

    @Override
    public Boolean undoThumb(DoThumbRequest doThumbRequest, HttpServletRequest request) {
        if (doThumbRequest == null || doThumbRequest.getId() == null) {
            throw new RuntimeException("参数错误");
        }
        User loginUser = userService.getLoginUser(request);
        // 加锁
        synchronized (loginUser.getId().toString().intern()) {

            // 编程式事务
            return transactionTemplate.execute(status -> {
                Long blogId = doThumbRequest.getId();
//                Thumb thumb = this.lambdaQuery()
//                        .eq(Thumb::getUserId, loginUser.getId())
//                        .eq(Thumb::getBlogId, blogId)
//                        .one();
                Long thumbId = ((Long) redisTemplate.opsForHash().get(ThumbConstant.USER_THUMB_KEY_PREFIX + loginUser.getId().toString(), blogId.toString()));
                if (thumbId == null) {
                    throw new RuntimeException("用户未点赞");
                }

                boolean update = blogService.lambdaUpdate()
                        .eq(Blog::getId, blogId)
                        .setSql("thumbCount = thumbCount - 1")
                        .update();

                boolean success = update && this.removeById(thumbId);
                if(success){
                    redisTemplate.opsForHash().delete(ThumbConstant.USER_THUMB_KEY_PREFIX + loginUser.getId().toString(), blogId.toString());
                }
                return success;
            });
        }
    }


    @Override
    public Boolean hasThumb(Long blogId, Long userId) {
        return redisTemplate.opsForHash().hasKey(RedisKeyUtil.getUserThumbKey(userId), blogId.toString());
    }


}




